package com.gongpingjialoan.activity.car;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.adapter.MeetRecordAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.MeetRecord;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.widget.LoadingDialog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 预约记录
 * Created by chuang on 2016/8/3.
 */
public class MeetRecordActivity extends BaseActivity implements NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener<ExpandableListView>, PullToRefreshBase.OnLastItemVisibleListener {

    public static final int CANCEL_MEET = 101;

    private PullToRefreshExpandableListView pullToRefreshListView;

    private ImageView nodataImageView;

    private ExpandableListView listView;

    private View footView;

    private List<MeetRecord> mMeetRecordList;

    private NetDataJson mNetDataJson;

    private NetDataJson mCancelMeetNetDataJson;

    private MeetRecordAdapter mContractAdapter;

    public int mPage;

    public boolean mIsLoadingMore = true;

    public boolean mHasMore;

    public boolean isRefresh;

    private LoadingDialog loadingDialog;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case CANCEL_MEET:
                    int id = msg.arg1;
                    String type = msg.obj.toString();
                    cancelMeet(id,type);
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        action = "my_appointRecord";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.meet_record_layout);
        setTitle("预约记录");
        footView = LayoutInflater.from(this).inflate(R.layout.listview_footview, null);
        nodataImageView = (ImageView) findViewById(R.id.no_info);
        pullToRefreshListView = (PullToRefreshExpandableListView) findViewById(R.id.listview);
        pullToRefreshListView.setScrollingWhileRefreshingEnabled(false);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setOnLastItemVisibleListener(this);
        mMeetRecordList = new ArrayList<>();
        mContractAdapter = new MeetRecordAdapter(mMeetRecordList, this,mHandler);

        listView = pullToRefreshListView.getRefreshableView();
        listView.addFooterView(footView);
        listView.setAdapter(mContractAdapter);
        listView.removeFooterView(footView);
        listView.setClipToPadding(false);
        listView.setGroupIndicator(null);
        //不能点击收缩：
        listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                return true;
            }
        });

        mNetDataJson = new NetDataJson(this);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                pullToRefreshListView.setRefreshing();
            }
        }, 300);
        loadingDialog = new LoadingDialog(this);
    }

    private void refresh() {
        mPage = 1;
        mHasMore = true;
        isRefresh = true;
        nodataImageView.setVisibility(View.GONE);
        updateData();

    }


    private void updateData() {
        mNetDataJson.cancelTask();
        mNetDataJson.addParam("page", mPage);
        mNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetDataJson.setUrl(API.meet_record);
        mNetDataJson.request("get");
    }


    @Override
    public void onLastItemVisible() {
        if (!mHasMore) {
            // Toast.makeText(this, "没有更多了", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!mIsLoadingMore && mHasMore) {
            listView.addFooterView(footView);
            listView.setSelection(listView.getBottom());
            isRefresh = false;
            mIsLoadingMore = true;
            mPage++;
            updateData();
        }
    }

    boolean isFristLoading = true;

    @Override
    public void onRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
        if (!isFristLoading) {
            String label =
                    "更新时间:" + DateUtils.formatDateTime(this, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
        }
        isFristLoading = false;
        refresh();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onDataJsonError(String errorMessage) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        mIsLoadingMore = false;
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
        pullToRefreshListView.onRefreshComplete();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
        if (mCancelMeetNetDataJson != null) {
            mCancelMeetNetDataJson.cancelTask();
            mCancelMeetNetDataJson = null;
        }
        if(mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
        }
        StepMonitor.getInstance().addMonitor(new Monitor("scroll", action, System.currentTimeMillis(), roll_pages));

    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        if (!isRefresh && mIsLoadingMore) {
            listView.removeFooterView(footView);
        }
        if(loadingDialog != null){
            loadingDialog.dismiss();
        }
        JSONArray jsonArray = null;
        if (isRefresh) {
            mMeetRecordList.clear();
            refreshList();
        }

        try {
            JSONObject jsonObject = json.getJSONObject("data");
            jsonArray = jsonObject.getJSONArray("appoints");
            if (0 == jsonArray.length()) {
                mIsLoadingMore = false;
                nodataImageView.setVisibility(View.VISIBLE);
                pullToRefreshListView.onRefreshComplete();
                return;
            }


            int size = jsonArray.length();
            for (int i = 0; i < size; i++) {
                MeetRecord mr = new MeetRecord();
                mr.appointList = new ArrayList<>();
                JSONObject object = jsonArray.getJSONObject(i);
                mr.date_time = object.getString("date_time");
                mr.type = object.getString("type");
                JSONArray jsonArray2 = object.getJSONArray("appoints");
                if (jsonArray2 != null) {
                    int size2 = jsonArray2.length();
                    for (int j = 0; j < size2; j++) {
                        JSONObject object2 = jsonArray2.getJSONObject(j);
                        MeetRecord.Appoint a = mr.new Appoint();
                        a.id = object2.getInt("id");
                        a.car_id = object2.getInt("car_id");
                        a.price = object2.getString("price");
                        a.eval_price = object2.getString("eval_price");
                        a.year = object2.getString("year");
                        a.month = object2.getString("month");
                        a.mile = object2.getString("mile");
                        a.pub_time = object2.getString("pub_time");
                        a.title = object2.getString("title");
                        a.appoint_address = object2.getString("appoint_address");
                        a.thumbnail = object2.getString("thumbnail");
                        a.status = object2.getString("status");
                        a.car_status = object2.getString("car_status");
                        a.city = object2.getString("city");
                        a.model_detail_zh = object2.getString("model_detail_zh");
                        a.model_zh = object2.getString("model_zh");
                        mr.appointList.add(a);
                    }
                }
                mMeetRecordList.add(mr);
            }
            int page_num = jsonObject.getInt("page_num");
            if (page_num == mPage) {
                mHasMore = false;
            }
        } catch (JSONException e) {
            mIsLoadingMore = false;
            mHasMore = false;
            nodataImageView.setVisibility(View.VISIBLE);
            Toast.makeText(this, "数据异常，请稍后再试", Toast.LENGTH_SHORT).show();
            pullToRefreshListView.onRefreshComplete();
            return;
        }
        refreshList();
        pullToRefreshListView.onRefreshComplete();
        mIsLoadingMore = false;
    }

    private void refreshList() {
        mContractAdapter.setData(mMeetRecordList);
        //首次加载全部展开：
        for (int i = 0; i < mMeetRecordList.size(); i++) {
            listView.expandGroup(i);
        }
    }

    private void cancelMeet(int id,String type) {
        loadingDialog.show();
        mCancelMeetNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                loadingDialog.cancel();
                Toast.makeText(MeetRecordActivity.this,errorMessage,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(JSONObject json) {
                Toast.makeText(MeetRecordActivity.this,"取消成功",Toast.LENGTH_SHORT).show();
                updateData();
            }
        });

        mCancelMeetNetDataJson.cancelTask();
        mCancelMeetNetDataJson.addParam("id", id);
        if("vip".equals(type)){
            mCancelMeetNetDataJson.setUrl(API.vip_meet_cancel);
        }else {
            mCancelMeetNetDataJson.addParam("device_code",GPJApplication.getInstance().getDeviceCode());
            mCancelMeetNetDataJson.setUrl(API.meet_cancel);
        }

        mCancelMeetNetDataJson.request("post");
    }

}
